package com.newasia.user.services;

import com.newasia.commons.tool.exception.ValidateException;
import com.newasia.user.ISysUserService;
import com.newasia.user.constants.SysRetCodeConstants;
import com.newasia.user.converter.SysUserConverter;
import com.newasia.user.dal.entitys.DealerInfo;
import com.newasia.user.dal.entitys.SysDealer;
import com.newasia.user.dal.entitys.SysUser;
import com.newasia.user.dal.entitys.SysUserRole;
import com.newasia.user.dal.persistence.SysDealerMapper;
import com.newasia.user.dal.persistence.SysRoleMapper;
import com.newasia.user.dal.persistence.SysUserMapper;
import com.newasia.user.dto.*;
import com.newasia.user.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Slf4j
@Service
public class SysUserServiceImpl implements ISysUserService {

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    SysUserConverter sysUserConverter;

    @Autowired
    SysDealerMapper sysDealerMapper;

    @Autowired
    SysRoleMapper sysRoleMapper;

    @Autowired
    RedissonClient redissonClient;

    @Override
    public SysUserLoginResponse selectUserByName(SysUserLoginRequest request) {
        log.info("Begin UserLoginServiceImpl.selectUserByName: userName:"+request.getUserName());
        SysUserLoginResponse response = new SysUserLoginResponse();
        try{
            SysUser sysUser=sysUserMapper.selectUserByName(request.getUserName());
            if(sysUser==null){
                return null;
            }
            DealerInfo dealer = sysDealerMapper.selectDealerByPrimaryKey(sysUser.getUserId());
            response=sysUserConverter.user2Res(sysUser);
            response.setDealerId(Long.valueOf(0));
            response.setMenuId(Long.valueOf(0));
            response.setDealerName(null);
            if(dealer!=null&&!"".equals(dealer)){
                response.setDealerId(dealer.getUserId());
                response.setMenuId(dealer.getMenuId());
                response.setDealerName(dealer.getDealerName());
            }
        }catch (Exception e){
            log.error("SysUserServiceImpl.selectUserByName Occur Exception :"+e);
        }
        return response;
    }

    @Override
    @Transactional
    public SysUserRegisterResponse register(SysUserRegisterRequest request) {
        log.info("Begin UserLoginServiceImpl.register: request:"+request);
        SysUserRegisterResponse response=new SysUserRegisterResponse();
        try {
            validUserRegisterRequest(request);

            if(request.getInvitedCode()!=null&&!"".equals(request.getInvitedCode())){
                RBucket rBucket =  redissonClient.getBucket(request.getInvitedCode());
                if(!rBucket.isExists()){
                    response.setCode(SysRetCodeConstants.INVITED_CODE_ERROR.getCode());
                    response.setMsg(SysRetCodeConstants.INVITED_CODE_ERROR.getMessage());
                    return response;
                }
            }

            SysUser user = new SysUser();
            user.setUserName(request.getUserName());
            user.setPassword(request.getUserPwd());
            user.setSalt(request.getSalt());
            user.setState("NORMAL");
            user.setCompanyName(request.getCompanyName());
            user.setFile(request.getFile());
            user.setEmail(request.getEmail());
            user.setMobile(request.getMobile());
            user.setCreatedTime(new Date());

            if(sysUserMapper.insert(user)!=1){
                response.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
                response.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
                return response;
            }
            SysUserRole userRole = new SysUserRole();
            userRole.setRoleId(request.getRoleId());
            userRole.setUserId(user.getUserId());

            if(sysRoleMapper.insertSysUserRole(userRole)!=1){
                response.setCode(SysRetCodeConstants.ROLE_INSERT_ERROR.getCode());
                response.setMsg(SysRetCodeConstants.ROLE_INSERT_ERROR.getMessage());
                return response;
            }

            if(request.getInvitedCode()!=null&&!"".equals(request.getInvitedCode())){
                RBucket rBucket =  redissonClient.getBucket(request.getInvitedCode());
                Long dealer_id = Long.valueOf(rBucket.get().toString());
                rBucket.delete();
                rBucket = redissonClient.getBucket(dealer_id.toString());
                rBucket.delete();
                SysDealer dealer = new SysDealer();
                dealer.setUserId(user.getUserId());
                dealer.setDealerId(dealer_id);
                dealer.setCreatTime(new Date());
                sysDealerMapper.insertSelective(dealer);
            }

            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        }catch (Exception e){
            log.error("SysUserLoginServiceImpl.register Occur Exception :"+e);
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }

    @Override
    public SysUserRegisterResponse updateUser(SysUserRegisterRequest request) {
        log.info("Begin UserLoginServiceImpl.register: request:"+request);
        SysUserRegisterResponse response=new SysUserRegisterResponse();
        try {
            SysUser user = new SysUser();
            user.setUserName(request.getUserName());
            user.setPassword(request.getUserPwd());
            user.setSalt(request.getSalt());
            user.setState("NORMAL");
            user.setCompanyName(request.getCompanyName());
            user.setFile(request.getFile());
            user.setEmail(request.getEmail());
            user.setMobile(request.getMobile());
            user.setUpdatedTime(new Date());

            if(sysUserMapper.updateByUserName(user)!=1){
                response.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
                response.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
                return response;
            }
            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        }catch (Exception e){
            log.error("SysUserLoginServiceImpl.register Occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }

    @Override
    public JoinDealerResponse joinDealer(JoinDealerRequest request) {
        log.info("Begin UserLoginServiceImpl.joinDealer: request:"+request);
        JoinDealerResponse response = new JoinDealerResponse();
        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        try{
            RBucket rBucket =  redissonClient.getBucket(request.getInvitedCode());
            if(!rBucket.isExists()){
                response.setCode(SysRetCodeConstants.INVITED_CODE_ERROR.getCode());
                response.setMsg(SysRetCodeConstants.INVITED_CODE_ERROR.getMessage());
                return response;
            }
            Long dealer_id = Long.valueOf(rBucket.get().toString());
            DealerInfo dealerInfo = sysDealerMapper.selectDealerByPrimaryKey(request.getUserId());
            if(dealerInfo!=null&&!"".equals(dealerInfo)){
                response.setCode(SysRetCodeConstants.DEALER_EXIST_ERROR.getCode());
                response.setMsg(SysRetCodeConstants.DEALER_EXIST_ERROR.getMessage());
                return response;
            }
            rBucket.delete();
            rBucket = redissonClient.getBucket(dealer_id.toString());
            rBucket.delete();
            SysDealer dealer = new SysDealer();
            dealer.setUserId(request.getUserId());
            dealer.setDealerId(dealer_id);
            dealer.setCreatTime(new Date());
            sysDealerMapper.insertSelective(dealer);
        }catch (Exception e){
            log.error("SysUserLoginServiceImpl.joinDealer Occur Exception :"+e);
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }

    //校验参数以及校验用户名是否存在
    private void validUserRegisterRequest(SysUserRegisterRequest request){
        request.requestCheck();
        SysUser user=sysUserMapper.validUserName(request.getUserName());
        if(user!=null&&!user.equals("")){
            throw new ValidateException(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode(),SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
        }
    }
}
